package jp.ac.u_tokyo.dch.dao.xmloutput;

import java.util.List;

import jp.ac.u_tokyo.dch.core.db.CustomPreparedStatement;
import jp.ac.u_tokyo.dch.core.db.DBConnection;
import jp.ac.u_tokyo.dch.core.exceptions.DBException;
import jp.ac.u_tokyo.dch.model.output.Attribute;
import jp.ac.u_tokyo.dch.util.common.CommonDBConnection;

public class OutputAttrDao {


	/**
	 * DBコネクションオブジェクト
	 */
	private DBConnection dbconn = null;

	/**
	 * 生成者
	 *
	 * @param DBコネクションオブジェクト
	 */
	public OutputAttrDao(DBConnection dbconn) {
		this.dbconn = dbconn;
	}


	public int[] insert(String schemaid, String tagId, List<Attribute> attrList) throws DBException {

		CustomPreparedStatement ps = null;
		int result[] = null;
		try{
			String query = "INSERT INTO output_attr (schemaid,tagid,name,value,outputorder)" +
			" VALUES (?,?,?,?,?)";

			ps = dbconn.prepareStatement(query);
			int order = 1;
			for (Attribute attr : attrList) {
				int index = 1;

				ps.setInt(index++, Integer.valueOf(schemaid));
				ps.setInt(index++, Integer.valueOf(tagId));
				ps.setString(index++, attr.getName());
				ps.setString(index++, attr.getValue());
				ps.setInt(index++, order);
				ps.addBatch();

				order++;
			}

			result = ps.executeBatch();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			CommonDBConnection.closeResource(ps);
		}
		return result;

	}

	public int delete(String schemaid) throws DBException {

		CustomPreparedStatement ps = null;
		int result = 0;
		try{
			String query = "DELETE FROM output_attr WHERE schemaid = ?";

			ps = dbconn.prepareStatement(query);

			int index = 1;
			ps.setInt(index++, Integer.valueOf(schemaid));

			result = ps.executeUpdate();

		}catch(DBException dbe){
			throw dbe;
		}finally{
			CommonDBConnection.closeResource(ps);
		}
		return result;
	}

}
